<template>
	<view class="dropdown">
		<view class="fixed-ba" @tap.stop="closeDropdown" v-if="isOpen"></view>
		<!-- <view @click="toggleDropdown" class="dropdown-button">{{ buttonText }}</view> -->
		<view class="dropdown-content" :class="{ 'show': isOpen, 'hide': !isOpen }" :style="dropdownStyle">
			<slot></slot>
		</view>
	</view>
</template>

<script>
	export default {
		async mounted() {
			this.dropdown_rect = await this.getSelect('.dropdown-content');
		},
		data() {
			return {
				isOpen: false,
				dropdownStyle: {
					top: '0px',
					left: '0px',
				},
				dropdown_rect: null
			};
		},
		props: {
			rect: {
				type: [Object], 
			},
		},
		watch: {
			rect(val) {
				if (val) {
					this.toggleDropdown();
				}
			}
		},
		methods: {
			toggleDropdown() {
				this.isOpen = !this.isOpen;
				const rect = this.rect;
				const rect2 = this.dropdown_rect;
				const rightEdge = rect.left + rect2.width;
				const bottomEdge = rect.bottom + rect2.height;
				// 获取系统屏幕宽高
				const systemInfo = uni.getSystemInfoSync();
				const screenWidth = systemInfo.screenWidth;
				const screenHeight = systemInfo.screenHeight;

				// 判断是否超出屏幕并调整位置
				let newLeft = rect.left;
				let newTop = rect.bottom + rect.height;
				if (rightEdge > screenWidth) {
					newLeft -= (rightEdge - screenWidth);
				}
				if (bottomEdge > screenHeight) {
					newTop -= (bottomEdge - screenHeight) + (rect2.height - rect.height);
				}
				if (this.isOpen) {
					this.dropdownStyle = {
						top: (newTop < 0 ? 0 : newTop) + 'px',
						left: (newLeft < 0 ? 0 : newLeft) + 'px',
					};
				}
			},
			closeDropdown() {
				this.isOpen = false;
				this.$emit('close', false)
			},

		},
	};
</script>

<style>
	.fixed-ba {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 99999999;
	}

	.dropdown {
		position: relative;
	}

	.dropdown .dropdown-button {
		padding: 8px 16px;
		border: 1px solid #ccc;
		border-radius: 4px;
		background-color: #f1f1f1;
		cursor: pointer;
		box-sizing: border-box;
	}



	.dropdown-content {
		visibility: hidden;
		position: fixed;
		background-color: #f9f9f9;
		min-width: 160px;
		box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
		padding: 12px;
		z-index: 99999999;
		transition: all 0.3s;
	}

	.dropdown-content.show {
		visibility: visible;
		animation-name: slideIn;
		animation-duration: 0.3s;
	}

	.dropdown-content.hide {
		animation-name: slideOut;
		animation-duration: 0.3s;
	}

	@keyframes slideIn {
		from {
			opacity: 0;
			transform: translateY(-10px);
		}

		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	@keyframes slideOut {
		from {
			opacity: 1;
			transform: translateY(0);
		}

		to {
			opacity: 0;
			transform: translateY(-10px);
		}
	}
</style>